﻿using System;
using System.Data;
using System.Data.OracleClient;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class Show_Report : BasicPage
{
    public string role;
    int col1 = 0;
    int col2 = 0;
    int col3 = 0;
    int col4 = 0;
    int col5 = 0;
    int col6 = 0;
    int col7 = 0;
    int col8 = 0;
    int col9 = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        role = GetRole();
        if (!IsPostBack)
        {            
            Attribute_Bind();
            Dep_Bind();
            DateBind();
            Auth();
            Report_Bind();
            SetCellPager();
            FlashNowBind();
            MoreBind();
        }
    }

    private void DateBind()
    {
        string sqlstr = "SELECT MAX(STARTED) FROM ALARM_TABLE_3G";
        Date3G.Text = "【3G】"+OracleHelper.ExecuteScalar(sqlstr, CommandType.Text, null).ToString();
        sqlstr = "SELECT MAX(ALARM_START_TIME) FROM ALARM_TABLE_2G";
        Date2G.Text = "【2G】"+OracleHelper.ExecuteScalar(sqlstr, CommandType.Text, null).ToString();
    }

    private void Auth()
    {
        if (!GetDep().Equals("市分"))
        {
            Dep_A.SelectedValue = GetDep();
            Dep_A.Enabled = false;
            Report.ShowFooter = false;
        }
    }

    private void SetCellPager()
    {
        PagedDataSource pds = new PagedDataSource();
        DataTable dt = GetCellView();
        CellPager.RecordCount = dt.Rows.Count;
        pds.DataSource = dt.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = CellPager.PageSize;
        pds.CurrentPageIndex = CellPager.CurrentPageIndex - 1;
        CellView.DataSource = pds;
        CellView.DataBind();
    }

    private void Report_Bind()
    {
        string sqlstr = "AB_GetInfo_Pk.GetUNLink";
		OracleParameter[] _params = {
                new OracleParameter("v_County",OracleType.VarChar,20),
				new OracleParameter("V_Begin",OracleType.VarChar,100),
				new OracleParameter("V_End",OracleType.VarChar,100),
				new OracleParameter("V_Type",OracleType.VarChar,100),
				new OracleParameter("resultSet",OracleType.Cursor)
            };
        _params[0].Value = Dep_A.SelectedValue=="0"?"":Dep_A.SelectedValue;
		_params[1].Value = Begin_Date.Text.Trim().Length>0?Begin_Date.Text.Trim():"";
		_params[2].Value = End_Date.Text.Trim().Length>0?End_Date.Text.Trim():"";
		_params[3].Value = GType_A.SelectedValue=="0"?"":GType_A.SelectedValue;
		_params[4].Direction = ParameterDirection.Output;
        DataTable dt = OracleHelper.ExecuteDataSet(sqlstr, CommandType.StoredProcedure, _params).Tables[0];
        if ((!string.IsNullOrEmpty(Report.Attributes["SortExpression"])) && (!string.IsNullOrEmpty(Report.Attributes["SortDirection"])))
        {
            dt.DefaultView.Sort = string.Format("{0} {1}", Report.Attributes["SortExpression"], Report.Attributes["SortDirection"]);
        }
        Report.DataSource = dt;
        Report.DataBind();
    }

    private void FlashNowBind()
    {
        string sqlStr = @"SELECT DISTINCT COUNTY,CELL_CHNAME
                                  FROM AB_CELL_UNLINK 
                                 WHERE CELL_CHNAME NOT IN (SELECT CELL_NAME FROM BLACK_LIST)
                                   AND START_TIME > TO_CHAR(SYSDATE,'yyyy-MM-dd')
                                 GROUP BY COUNTY,CELL_CHNAME,trunc(START_TIME,'HH24')
                                HAVING Count(1) >= 3
                                 UNION ALL
                                SELECT SUBSTR(T2.CELL_CHNAME,0,2) AS COUNTY,T2.CELL_CHNAME
                                  FROM ALARM_TABLE_3G T1
                                  LEFT JOIN CELL_CLASS T2
                                    ON T1.RNW_OBJECT_NAME = T2.CELL_ENNAME
                                 WHERE STARTED IS NOT NULL
                                   AND STARTED > TO_CHAR(SYSDATE,'yyyy-MM-dd')
                                   AND T2.CELL_CHNAME IS NOT NULL
                                   AND T2.CELL_CHNAME NOT IN (SELECT CELL_NAME FROM BLACK_LIST)   
                                   AND C_NUMBER = '7786'   
                                   AND TO_NUMBER((T1.CANCELED- T1.STARTED)*24*60) >= 1
                                   AND (TO_NUMBER(TO_CHAR(T1.STARTED,'HH24'))>5
                                    OR (NVL(TO_NUMBER(TO_CHAR(T1.CANCELED,'HH24')),0)>5 OR T1.CANCELED IS NULL))
                                 GROUP BY SUBSTR(T2.CELL_CHNAME,0,2),T2.CELL_CHNAME,trunc(T1.STARTED,'HH24')
                                HAVING COUNT(1) >= 3";
        DataSet ds = OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
        if (ds.Tables[0].Rows.Count > 0)
        {
            FlashNow.DataSource = ds;
            FlashNow.DataBind();
            FlashDiv.Visible = true;
        }
    }

    private void MoreBind()
    {
        string sqlStr = @"SELECT cell_chname,trunc((SYSDATE - START_TIME) * 24) as dual
                                  FROM AB_CELL_UNLINK 
                                 WHERE CELL_CHNAME NOT IN (SELECT CELL_NAME FROM BLACK_LIST)
                                   AND (SYSDATE - START_TIME) * 24 >= 24
                                   AND (SYSDATE - START_TIME) * 24 <= 72
                                   AND RECOVER_TIME IS NULL
                                    UNION ALL
                                    SELECT cell_chname,trunc((SYSDATE-STARTED)*24) as dual 
                                  FROM ALARM_TABLE_3G T1
                                  LEFT JOIN CELL_CLASS T2
                                    ON T1.RNW_OBJECT_NAME = T2.CELL_ENNAME
                                 WHERE STARTED IS NOT NULL
                                   AND (SYSDATE-STARTED)*24>=24
                                   AND (SYSDATE-STARTED)*24<=72
                                   AND CANCELED IS NULL
                                   AND T2.CELL_CHNAME IS NOT NULL
                                   AND T2.CELL_CHNAME NOT IN (SELECT CELL_NAME FROM BLACK_LIST)   
                                   AND C_NUMBER = '7786'   
                                   AND (T1.CANCELED IS NULL OR TO_NUMBER((T1.CANCELED- T1.STARTED)*24*60) >= 1)
                                   AND (TO_NUMBER(TO_CHAR(T1.STARTED,'HH24'))>5
                                    OR (NVL(TO_NUMBER(TO_CHAR(T1.CANCELED,'HH24')),0)>5 OR T1.CANCELED IS NULL))
                                   ORDER BY dual DESC";
        DataSet ds = OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MoreWarm.DataSource = ds;
            MoreWarm.DataBind();
            MoreDiv.Visible = true;
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }

    private DataTable GetCellView()
    {
        string sqlstr = "AB_GetInfo_Pk.GetCell";
        OracleParameter[] _params = {
                new OracleParameter("v_County",OracleType.VarChar,20),
				new OracleParameter("V_Begin",OracleType.VarChar,100),
				new OracleParameter("V_End",OracleType.VarChar,100),
				new OracleParameter("V_Type",OracleType.VarChar,100),
				new OracleParameter("resultSet",OracleType.Cursor)
            };
        _params[0].Value = Dep_A.SelectedValue == "0" ? "" : Dep_A.SelectedValue;
        _params[1].Value = Begin_Date.Text.Trim().Length > 0 ? Begin_Date.Text.Trim() : "";
        _params[2].Value = End_Date.Text.Trim().Length > 0 ? End_Date.Text.Trim() : "";
        _params[3].Value = GType_A.SelectedValue == "0" ? "" : GType_A.SelectedValue;
        _params[4].Direction = ParameterDirection.Output;
        DataTable dt = OracleHelper.ExecuteDataSet(sqlstr, CommandType.StoredProcedure, _params).Tables[0];
        if ((!string.IsNullOrEmpty(CellView.Attributes["SortExpression"])) && (!string.IsNullOrEmpty(CellView.Attributes["SortDirection"])))
        {
            dt.DefaultView.Sort = string.Format("{0} {1}", CellView.Attributes["SortExpression"], CellView.Attributes["SortDirection"]);
        }
        return dt;
    }

    private void Dep_Bind()
    {
        string sqlstr = "SELECT DISTINCT SUBSTR(CELL_CHNAME,0,2) AS County FROM CELL_CLASS ORDER BY SUBSTR(CELL_CHNAME,0,2)";
        Dep_A.DataSource = OracleHelper.ExecuteDataSet(sqlstr, CommandType.Text, null).Tables[0].DefaultView;
        Dep_A.DataTextField = "County";
        Dep_A.DataValueField = "County";
        Dep_A.DataBind();
        Dep_A.Items.Insert(0, new ListItem("全市", "0"));
    }

    private void Attribute_Bind()
    {
        Begin_Date.Text = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
        Begin_Date.Attributes.Add("onclick", "WdatePicker({el:$dp.$('BeginDate'),dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d %H:%m:%s',startDate:'%y-%M-01 00:00:00,alwaysUseStartDate:true'});");
        End_Date.Attributes.Add("onclick", "WdatePicker({el:$dp.$('EndDate'),dateFmt:'yyyy-MM-dd HH:mm:ss',maxDate:'%y-%M-%d %H:%m:%s'});");
        Report.Attributes.Add("SortExpression", "UNLINK");
        Report.Attributes.Add("SortDirection", "DESC");
        CellView.Attributes.Add("SortExpression", "UNLINK");
        CellView.Attributes.Add("SortDirection", "DESC");
    }

    protected void CellView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            Response.Redirect("Detail.aspx?xf=" + Dep_A.SelectedValue + "&jz=" + e.CommandArgument.ToString() + "&GType=" + GType_A.SelectedValue + "&BeginDate="
                + Begin_Date.Text + "&EndDate=" + End_Date.Text);
        }
        else if (e.CommandName == "Black")
        {
            if (AddBlack(e.CommandArgument.ToString()) > 0)
            {
                Report_Bind();
                SetCellPager();
                Page.ClientScript.RegisterStartupScript(this.GetType(), "success"
                    , "$(function() {alert('已加入黑名单！');})", true);
            }
        }
    }

    private int AddBlack(string argCell)
    {
        string sqlstr = "INSERT INTO BLACK_LIST VALUES(:CELL_NAME,sysdate)";
        OracleParameter[] _params = {
                new OracleParameter(":CELL_NAME",OracleType.NVarChar,100)
            };
        _params[0].Value = argCell;
        return OracleHelper.ExecuteNonQuery(sqlstr, CommandType.Text, _params);
    }

    protected void CellPager_PageChanged(object sender, EventArgs e)
    {
        SetCellPager();
    }

    protected void Query_Click(object sender, EventArgs e)
    {        
        Report_Bind();
        CellPager.CurrentPageIndex = 1;
        SetCellPager();
        FlashNowBind();
        MoreBind();
    }

    protected void Excel_Click(object sender, EventArgs e)
    {
        DGToExcel(Report,Dep_A.Enabled?"UTF-8":"GB2312");
    }
    protected void Report_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (DataControlField dataControlField in Report.Columns)
            {
                if (dataControlField.SortExpression.Equals(Report.Attributes["SortExpression"]))
                {
                    Label label = new Label();
                    label.Text = Report.Attributes["SortDirection"].Equals("ASC") ? "▲" : "▼";
                    e.Row.Cells[Report.Columns.IndexOf(dataControlField)].Controls.Add(label);
                }
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView row = (DataRowView)e.Row.DataItem;
            col2+= Convert.ToInt32(row[1].ToString());
            col3 += Convert.ToInt32(row[10].ToString());
            col4 += Convert.ToInt32(row[3].ToString());
            col5 += Convert.ToInt32(row[4].ToString());
            col6 += Convert.ToInt32(row[11].ToString());
            col7 += Convert.ToInt32(row[6].ToString());
            col8 += Convert.ToInt32(row[7].ToString());
            col9 += Convert.ToInt32(row[8].ToString());
            col1 += Convert.ToInt32(row[9].ToString());
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#D5E5EA'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[0].Text = "合计";
            e.Row.Cells[1].Text = col1.ToString();
            e.Row.Cells[2].Text = col2.ToString();
            e.Row.Cells[3].Text = SecondToHMS(col3);
            e.Row.Cells[4].Text = col4.ToString();
            e.Row.Cells[5].Text = col5.ToString();
            e.Row.Cells[6].Text = SecondToHMS(col6);
            e.Row.Cells[7].Text = col7.ToString();
            e.Row.Cells[8].Text = col8.ToString();
            e.Row.Cells[9].Text = col9.ToString();
            e.Row.CssClass = "cssFooter";
        }
    }

    private string SecondToHMS(int argSd)
    {
        return Convert.ToString(argSd / 3600) + ":" + Convert.ToString((argSd - argSd / 3600 * 3600) / 60).PadLeft(2,'0')
            + ":" + Convert.ToString(argSd % 60).PadLeft(2,'0');
    }

    protected void Report_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“逆序”
        string sortDirection = "DESC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == Report.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (Report.Attributes["SortDirection"].ToString() == sortDirection ? "ASC" : "DESC");
        }

        // 重新设定GridView排序数据列及排序方向
        Report.Attributes["SortExpression"] = sortExpression;
        Report.Attributes["SortDirection"] = sortDirection;

        Report_Bind();
    }

    protected void Cell_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“逆序”
        string sortDirection = "DESC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == CellView.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (CellView.Attributes["SortDirection"].ToString() == sortDirection ? "ASC" : "DESC");
        }

        // 重新设定GridView排序数据列及排序方向
        CellView.Attributes["SortExpression"] = sortExpression;
        CellView.Attributes["SortDirection"] = sortDirection;

        SetCellPager();
    }

    protected void CellView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (DataControlField dataControlField in CellView.Columns)
            {
                if (dataControlField.SortExpression.Equals(CellView.Attributes["SortExpression"]))
                {
                    Label label = new Label();
                    label.Text = CellView.Attributes["SortDirection"].Equals("ASC") ? "▲" : "▼";
                    e.Row.Cells[CellView.Columns.IndexOf(dataControlField)].Controls.Add(label);
                }
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#D5E5EA'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
        }
    }
}
